package hub.cathome.controller;

import hub.annotation.Affairs;
import hub.annotation.NotImplementation;
import hub.annotation.View;
import hub.cathome.entity.Page;
import hub.cathome.entity.ShotBlog;
import hub.cathome.entity.User;
import hub.cathome.entity.Want;
import hub.cathome.service.HashPassword;
import hub.cathome.service.ProjService;
import hub.cathome.service.ShotBlogService;
import hub.cathome.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Controller
@SessionAttributes(names={"user"},types = {User.class})
public class AuthenticationController {
    @Resource(name="shotBlogService")
    private ShotBlogService shotBlogService;
    @Resource(name="userService")
    private UserService userService;
    @Resource(name="projService")
    private ProjService projService;
    @View("首页")
    @RequestMapping(value={"/","/index"})
    public String indexPage(@RequestParam(value = "pageNumber",required = false) Integer pageNumber, Model model, HttpSession session){
        Page page = (Page) session.getAttribute("shotBlogPage");

        if(page==null){
            page = new Page();
            page.setPage(1,projService.getProjById(1).getShotBlogPageSize());
            page.setMaxPage((int) Math.ceil(((double)shotBlogService.getShotBlogCount())/page.getPageSize()));
        }else{
            page.setMaxPage((int) Math.ceil(((double)shotBlogService.getShotBlogCount())/page.getPageSize()));
        }
        if(pageNumber==null){
            page.setPageNumber(1);
            pageNumber = 1;
        }else{
            if(pageNumber==-2){
                //上一页
                pageNumber = page.getPageNumber()-1;
            }else if(pageNumber==-1){
                //下一页
                pageNumber = page.getPageNumber()+1;
            }
            while(pageNumber>page.getMaxPage()){
                pageNumber--;
            }
            if(pageNumber<=0){
                pageNumber = 1;
            }
            page.setPageNumber(pageNumber);
        }

        List<ShotBlog> shotBlogList = shotBlogService.getSome(page.getCurrentBegin(),page.getPageSize());
        model.addAttribute("shotBlogList",shotBlogList);
        ArrayList<Integer> pages = new ArrayList<>();
        for(int i = pageNumber,j=0;i<=page.getMaxPage()&&j<5;i++,j++){
            pages.add(i);
        }
        model.addAttribute("pages",pages);
        return "home/index";
    }
    @View("登录视图")
    @GetMapping("/login")
    public String loginView(){
        return "home/login";
    }
    @View("注册视图")
    @GetMapping("/register")
    public String registerView(){
        return "home/register";
    }
    @Resource(name="hashPassword")
    private HashPassword hashPassword;
    @NotImplementation
    @Affairs("登录")
    @RequestMapping("/active/login")
    public String login(@RequestParam String username, @RequestParam String password, Model model, HttpServletRequest request, HttpServletResponse response){
        Long hashedPassword = hashPassword.createKey(password);
        if(userService.login(username,hashedPassword)>0){
            User user = userService.getUserByComplexName(username);
            model.addAttribute("user",user);
            request.getSession().setAttribute("user",user);
            Cookie cookie = new Cookie("username",username);
            Cookie cookie2 = new Cookie("password",hashedPassword+"");
            cookie.setMaxAge(24*3600*3);
            cookie2.setMaxAge(24*3600*3);
            response.addCookie(cookie);
            response.addCookie(cookie2);
            System.out.println(request.getContextPath());
            System.out.println(request.getRequestURI());
//             在网页中利用cookie实现找到cookie中的用户密码，cookie保存3天
            return "redirect:/home";
        }else{
            model.addAttribute("tip","登陆失败");
            return "redirect:/login";
        }

    }
    @NotImplementation
    @Affairs("注册")
    @RequestMapping("/active/register")
    public String register(@Validated Want want, Errors errors, Model model, HttpServletResponse response, HttpServletRequest request){
        if(errors.hasErrors()){
            return "error/error";
        }
        User user = new User();
        user.setUsername(want.getUsername());
        user.setNickname(want.getNickname());
        user.setPassword(hashPassword.createKey(want.getPassword()));
        int x = 0;
        if(userService.getUserCountByComplexName(want.getUsername())>=1){
            model.addAttribute("sameUsername",want.getUsername());
            x++;
        }
        if(userService.getUserCountByComplexName(want.getNickname())>=1){
            model.addAttribute("sameNickname",want.getNickname());
            x++;
        }
        if(x>0){
            model.addAttribute("same","1");
            return "error/error";
        }
        userService.insertUser(user);
        model.addAttribute("tip","登陆成功");
        model.addAttribute("user",user);
        Cookie cookie = new Cookie("username",user.getUsername());
        Cookie cookie2 = new Cookie("password",user.getPassword()+"");
        cookie.setMaxAge(24*3600*3);
        cookie2.setMaxAge(24*3600*3);
        response.addCookie(cookie);
        response.addCookie(cookie2);
        System.out.println(request.getContextPath());
        System.out.println(request.getRequestURI());
        return "redirect:/index";
    }

    @Affairs("注销登录")
    @RequestMapping("/affair/logout")
    public String logout(SessionStatus sessionStatus){
        sessionStatus.setComplete();
        return "redirect:/index";
    }
}
